﻿#region Copyright information
// 
// Copyright © 2005-2013 Yongkee Cho. All rights reserved.
// 
// This code is a part of the Biological Object Library and governed under the terms of the
// GNU Lesser General  Public License (LGPL) version 2.1 which accompanies this distribution.
// For more information on the LGPL, please visit http://bol.codeplex.com/license.
// 
// - Filename: ArgMin.cs
// - Author: Yongkee Cho
// - Email: yongkeecho@gmail.com
// - Date Created: 2012-09-06 11:39 AM
// - Last Modified: 2013-01-25 3:59 PM
// 
#endregion
using System;
using System.Collections.Generic;
using System.Linq;

namespace BOL.Linq.Descriptive
{
    public static partial class Descriptive
    {
        public static int ArgMin<T>(this IEnumerable<T> source)
            where T : IComparable<T>
        {
            var list = source.ToList();
            var i = 0;
            var argMin = 0;
            var min = list.FirstOrDefault();

            foreach (var element in list)
            {
                if (element.CompareTo(min) <= 0)
                {
                    argMin = i;
                    min = element;
                }

                i++;
            }

            return argMin;
        }

        public static TKey ArgMin<TKey, TValue>(this IDictionary<TKey, TValue> source)
            where TValue : IComparable<TValue>
        {
            var keyMin = default(TKey);
            var min = source.Values.FirstOrDefault();

            foreach (var key in source.Keys)
            {
                if (source[key].CompareTo(min) <= 0)
                {
                    keyMin = key;
                    min = source[key];
                }
            }

            return keyMin;
        }

        public static TSource ArgMin<TSource, TResult>(this IEnumerable<TSource> source, Converter<TSource, TResult> converter)
            where TResult : IComparable<TResult>
        {
            if (converter == null)
                throw new ArgumentNullException("converter");

            var argMin = default(TSource);
            var minResult = default(TResult);

            foreach (var element in source)
            {
                var result = converter(element);

                if (result.CompareTo(minResult) <= 0)
                {
                    argMin = element;
                    minResult = result;
                }
            }

            return argMin;
        }
    }
}
